package com.cssw.fyzb.core.mao.live;

import com.cssw.fyzb.core.model.mos.AudienceMo;
import com.cssw.fyzb.core.model.mos.LivePkMo;
import com.cssw.fyzb.core.mongo.MongoClient;
import com.cssw.fyzb.core.util.DocUtil;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Feng Chen
 */
@Component
public class LivePkMaoImpl implements LivePkMao {

    @Autowired
    private MongoClient mongoClient;

    @Override
    public void create(Long liveId, Long pkId) {
        LivePkMo pkMo = new LivePkMo();
        pkMo.setLiveId(liveId);
        pkMo.setPkId(pkId);
        pkMo.setTotal(0);
        pkMo.setAudiences(Collections.emptyList());
        mongoClient.getCollection("live_pk").insertOne(DocUtil.encode(pkMo));
    }

    @Override
    public LivePkMo findByLiveAndPk(Long liveId, Long pkId) {
        Document doc = mongoClient.getCollection("live_pk")
                .find(new Document("liveId", liveId).append("pkId", pkId))
                .first();
        return DocUtil.decoce(doc, LivePkMo.class);
    }

    @Override
    public List<LivePkMo> findByPk(Long pkId) {
        List<Document> docs = new ArrayList<>();
        mongoClient.getCollection("live_pk")
                .find(new Document("pkId", pkId)).into(docs);

        List<LivePkMo> list = new ArrayList<>();
        for (Document doc : docs) {
            list.add(DocUtil.decoce(doc, LivePkMo.class));
        }

        return list;
    }

    @Override
    public boolean exists(Long liveId, Long pkId, Long userId) {
        Document query = new Document()
                .append("liveId", liveId)
                .append("pkId", pkId)
                .append("audiences.userId", userId);

        Document doc = mongoClient.getCollection("live_pk")
                .find(query)
                .first();

        return doc != null;
    }

    @Override
    public void enterPk(Long liveId, Long pkId, Long userId) {
        AudienceMo audience = new AudienceMo();
        audience.setUserId(userId);
        audience.setState("1");
        audience.setReward(0);
        mongoClient.getCollection("live_pk").updateOne(
                new Document("liveId", liveId).append("pkId", pkId),
                new Document().append("$push", new Document("audiences", DocUtil.encode(audience)))
        );
    }

    @Override
    public void incReward(Long liveId, Long pkId, Long userId, Integer reward) {
        Document query = new Document()
                .append("liveId", liveId)
                .append("pkId", pkId)
                .append("audiences.userId", userId);
        Document set = new Document()
                .append("$inc", new Document().append("audiences.$.reward", reward).append("total", reward));
        mongoClient.getCollection("live_pk").updateOne(query, set);
    }

}
